﻿using HtmlAgilityPack;
using Model.CustomApp;
using OpenInterface;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using IRepository;

namespace OpenImplement
{
    public class AnalyzeStdGov : IAnalyzer
    {
        private IDefaultRepository<StdGovStdDetailModel> defaultRepository  = null;
        public AnalyzeStdGov()
        {
            defaultRepository = Service.ServiceManager.GetService<IDefaultRepository<StdGovStdDetailModel>>();
        }

        public void Analyze(string url, string html, Action<string, HandlerType> actHandlerUrl)
        {
            //列表页
            if (url.Contains("stdPage"))
            {
                var urlInfo = url.Split(new String[] { "pageNo=" }, StringSplitOptions.None);
                //解析详情页地址
                var regex = new Regex(@"pid=""(?<pid>.*)"" target", RegexOptions.IgnoreCase);
                if (regex.IsMatch(html))
                {
                    foreach (Match item in regex.Matches(html))
                    {
                        var pid = item.Groups["pid"].Value;
                        var detailUrl = "http://www.std.gov.cn/gb/search/gbDetailed?id=" + pid;
                        actHandlerUrl.Invoke(detailUrl, HandlerType.ReSetDepth);
                    }
                    //往下翻页
                    actHandlerUrl.Invoke(string.Format("{0}pageNo={1}", urlInfo[0], int.Parse(urlInfo[1]) + 1),HandlerType.ReSetDepth);
                }
                else
                {
                    Console.WriteLine("-----Analyzer Analyze----重新采集:" +url);
                    actHandlerUrl.Invoke(url, HandlerType.ReCollect);
                }
            }
            ///详情页
            else if (url.Contains("gbDetailed"))
            {
                var stdInfo = new StdGovStdDetailModel() { Url = url};

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                var root = doc.DocumentNode.SelectSingleNode("/html/body/div[3]/div/div/div");
                var stdNameNode = root.SelectSingleNode("div[1]/h4");
                var enStdNameNode = root.SelectSingleNode("div[1]/h5");

                stdInfo.StdName = stdNameNode.InnerText;
                stdInfo.ENStdName = enStdNameNode.InnerText;
                foreach (var node in root.SelectNodes("div"))
                {
                    if (node.InnerText.Contains("标准号"))
                    {
                        var dts = node.Descendants("dt").Select(n=>n.InnerText).ToList();
                        var dds = node.Descendants("dd").Select(n => n.InnerText).ToList();
                        var builder = new List<string>();
                        for (int i = 0; i < dts.Count; i++)
                        {
                            var dt = dts[i];
                            var dd = dds[i];

                            builder.Add(string.Format("{0}={1}", dt, dd));

                            if (dt.Contains("标准号"))
                                stdInfo.StdNo = dd;
                            else if (dt.Contains("发布日期"))
                                stdInfo.PubDate =dd;
                            else if (dt.Contains("实施日期"))
                                stdInfo.ImpDate = dd.Replace("", "\r", "\n", "\t");
                            else if (dt.Contains("中国标准分类"))
                                stdInfo.CHStdCls = dd;
                            else if (dt.Contains("国际标准分类"))
                                stdInfo.NaStdCls = dd;
                            else if (dt.Contains("归口"))
                                stdInfo.GKUnit = dd;
                            else if (dt.Contains("执行"))
                                stdInfo.ZXUnit = dd;
                            else if (dt.Contains("主管"))
                                stdInfo.ZGUnit = dd;
                        }
                        stdInfo.BaseInfo = string.Join(";", builder);
                        
                        break;
                    }
                }
                var ps = root.Descendants("p");
                foreach (var node in ps)
                {
                    if (node.InnerHtml.Contains("起草单位"))
                    {
                        var unitNodes = node.Descendants("span");
                        stdInfo.QCUnit = string.Join(",", unitNodes.Select(n => n.InnerText));

                    }
                    if (node.InnerHtml.Contains("起草人"))
                    {
                        var authorNodes = node.Descendants("span");
                        stdInfo.Author = string.Join(",", authorNodes.Select(n => n.InnerText));
                        break;
                    }
                }
                defaultRepository.Add(stdInfo, Common.Constant.AppSetting.DefaultDataConstr);

            }
            else
            {
                Console.WriteLine("解析不成功");
            }
        }
    }
}
